package team.stride.tabs.home;

import team.stride.R;
import team.stride.database.StrideDB;
import team.stride.tabs.TabGroupActivity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;

public class HomeActivity extends Activity {
	private TextView maxKm;
	private TextView totalKm;
	private TextView topSpeed;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_layout);

		maxKm = (TextView) findViewById(R.id.homeMaxDistTV);
		totalKm = (TextView) findViewById(R.id.homeTotalDistance);
		topSpeed = (TextView) findViewById(R.id.homeTopSpeed);

		setKilometers();

		final TabGroupActivity parentActivity = (TabGroupActivity) getParent();
		parentActivity.closeAllChildsExceptLastOne();

		final Button newTrackBtn = (Button) findViewById(R.id.new_track_btn);

		OnTouchListener newTrackListener = new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					Intent intent = new Intent(getParent(),
							NewTrackActivity.class);
					TabGroupActivity parentActivity = (TabGroupActivity) getParent();
					parentActivity.startChildActivity("NewTrackActivity",
							intent);
					return true;
				}
				return false;
			}
		};
		newTrackBtn.setOnTouchListener(newTrackListener);
	}

	private void setKilometers() {
		Cursor cursor = managedQuery(StrideDB.CONTENT_URI_RESULTS, null, null,
				null, null);
		float max = 0;
		float total = 0;
		float speed = 0;
		while (cursor.moveToNext()) {
			final int length_index = cursor.getColumnIndex(StrideDB.LENGTH_R);
			final int speed_index = cursor.getColumnIndex(StrideDB.TOPSPEED_R);

			float length = cursor.getFloat(length_index);
			float crtSpeed = cursor.getFloat(speed_index);
			if (length > max)
				max = length;
			if (crtSpeed > speed)
				speed = crtSpeed;
			total += length;
		}
		cursor.close();

		maxKm.setText(max + " Km");
		totalKm.setText(total + " Km");
		topSpeed.setText(speed + " Km/h");
	}
}
